package mcom.cmutweet;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;

import ch.ethz.twimight.activities.ShowTweetListActivity;


import android.os.AsyncTask;
import android.util.Log;

public class RoutineTasks {
	private static final String TAG = "RoutineTasks";
	
	public static final String host = "tarun.isr.cs.cmu.edu";
	public static final String logUrl = "https://"+host+"/cmutweet/log.php";
	public static final String nudgeUrl = "http://"+host+"/get_nudge_option.php";
	
	public static final String SP_NUDGE = "NudgeChoice";
	public static final String SP_NUDGETABICON = "NudgeUserTabIcon";
	
	
	/** Launch at ShowTweetListActivity, get Nudge choice from server, and save into SharedPreference */
	public static class NudgeChoiceTask extends AsyncTask<Long, Void, Integer>{
		
		@Override
		protected Integer doInBackground(Long... params) {
			long userID = params[0];
			ArrayList<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("user_id", userID+""));
			
			int nudge_choice = -1;
			try{
				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httpPost = new HttpPost(nudgeUrl);
				httpPost.setEntity(new UrlEncodedFormEntity(nvps));

				//Log.i(TAG, httpPost.getURI().toString());

				HttpResponse httpResponse = httpClient.execute(httpPost);
				HttpEntity entity = httpResponse.getEntity();
				InputStream is = entity.getContent();
				BufferedReader br = new BufferedReader(new InputStreamReader(
						is, "iso-8859-1"), 8);
				StringBuilder sb = new StringBuilder();
				String line;
				while ((line = br.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				String result = sb.toString();

				if (result.equals("null")) {
					// TODOIF: send log message that we did not find the record
				} else {
					JSONArray jArray = new JSONArray(result);
					nudge_choice = jArray.getJSONObject(0).getInt("nudge");
				}
			} catch (Exception e) {
				Log.e(TAG, "Error " + e.getLocalizedMessage());
			}
			
			if(nudge_choice==-1){
				Log.i(TAG, "No Nudge Choice Found");
				nudge_choice = LogJSON.NUDGE_NONE;
			}
			return nudge_choice;
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
			if(ShowTweetListActivity.curPtr != null){
				ShowTweetListActivity.curPtr.onNudgeChoiceTaskFinish(result);
			}
		}
	}
	
	
	/** Start to send a log to the server */
	public static void startLogTask(long timestamp, String user_id, String tag, String content){
		String[] params = new String[4];
    	params[0] = user_id;
    	params[1] = timestamp+"";
    	params[2] = tag;
    	params[3] = content;
		new LogActionTask().execute(params);
	}

	public static final String LOG_LOGIN = "login";
	public static final String LOG_CREDENTIAL = "credential";
	public static final String LOG_LOGOUT = "logout";
	public static final String LOG_TWEET = "tweet";
	public static final String LOG_ICON = "icon";
	
	static class LogActionTask extends AsyncTask<String, Void, Void>{
		@Override
		protected Void doInBackground(String... params){
			String userID = params[0];
	        String timestamp = params[1];
	        String tag = params[2];
	        String content = params[3];
	        
	        ArrayList<NameValuePair> nvps = new ArrayList<NameValuePair>();
	        nvps.add(new BasicNameValuePair("user_id", userID));
	        nvps.add(new BasicNameValuePair("timestamp", timestamp));
	        nvps.add(new BasicNameValuePair("tag", tag));
	        nvps.add(new BasicNameValuePair("content", content));
	        
	        //Send the message to PHP server
	        try{
	        	HttpResponse httpResponse = HttpsConn.httpsPost(logUrl, nvps);
	        	//Log.i(TAG, "Status: "+ httpResponse.getStatusLine().toString()+"\n"
	        	//		+"Tag: "+tag+"\n"+"Content: "+content);
	        	
	        	if(httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK){
	        		Log.e(TAG, "Failed to add to remote server");
	        	}
	        	else{
	        		String responseStr = "NULL";
	        		HttpEntity httpEntity = httpResponse.getEntity();
	        		if(httpEntity!=null){
	        			responseStr = EntityUtils.toString(httpEntity);
	        		}
	        		Log.i(TAG, "Added to remote server successfully. Response: "+responseStr);
	        	}
	        }catch(Exception e){
	        	Log.e(TAG, "Log Task fail: "+e.toString());
	        }
	        return null;
		}
    }
	
	
}
